package api

import (
	"encoding/json"
	"evtest/evcs"
	"evtest/util/app"
	"evtest/util/e"
	"evtest/ventpipe"
	"fmt"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func StationInfos(c *gin.Context) {
	appG := app.Gin{C: c}
	pageNo, _ := strconv.Atoi(c.DefaultQuery("pageno", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pagesize", "10"))
	queryStationsInfo := evcs.QueryStationsInfo{
		PageNo:   pageNo,
		PageSize: pageSize,
	}
	jsonParam, _ := queryStationsInfo.ToJson()
	postMessage := &ventpipe.PostMessage{
		ApiUrl:     "query_stations_info",
		JsonParam:  jsonParam,
		OutputChan: make(chan *ventpipe.PipeRsp),
	}
	ventpipe.AscendPipe.InputChan <- postMessage
	timer := time.NewTimer(time.Second * 2)
	stationInfoRsp := &ventpipe.PipeRsp{}
	select {
	case <-timer.C:
		fmt.Println("fetch station time out. ")
	case stationInfoRsp = <-postMessage.OutputChan:
		fmt.Printf("[%s] the station info received.\nRet: %d\nOptCode: %d\nErr: %#v\n", time.Now().Format("2006-01-02 15:04:05"), stationInfoRsp.Ret, stationInfoRsp.OptCode, stationInfoRsp.Err)
	}
	var stationInfoResponse evcs.StationInfoResponse
	err := json.Unmarshal(stationInfoRsp.Data, &stationInfoResponse)
	if err != nil {
		appG.ErrorWithMsg(e.JSON_PARAMS, err.Error())
		return
	}
	appG.Success(stationInfoResponse)
}
